import React, { Component } from 'react';
import { Relax } from 'iflux2';
import { Map, OrderedSet } from 'immutable';

import { Table, Row, Col, Button, Spin, Modal, message } from 'antd';

import { listQL } from '../ql';
import { orderColumns } from '../constant/columns';

import OrderIterm from './order-item';
import CommentDetail from './comment-detail';
import Pages from './pages';
import EmptyBody from './empty-body';

import noop from 'util/noop';


@Relax
export default class OrderList extends Component {
    static defaultProps = {
        list: listQL,
        pagination: Map(),
        loading: true,
        setCommentDetail: noop,
        deleteComments: noop,
        updateCommentShowState: noop
    };


    constructor(props) {
        super(props);

        this.state = {
            selectedRowKeys: [],
            filterName: '所有商品评价',
            filters: [],
            // 控制评论的显示状态
            commentVisible: false

        }
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.pagination.get('pageNum') !== nextProps.pagination.get('pageNum')) {
            this.setState({
                selectedRowKeys: []
            })
        }
    }


    render() {
        const { list, loading } = this.props;
        const { selectedRowKeys } = this.state;

        const rowSelection = {
            selectedRowKeys: selectedRowKeys,
            onSelectAll: (selected, selectedRows, changeRows) => this.selectAll(selected, selectedRows, changeRows),
            getCheckboxProps: record => ({
                // 如果一笔订单下的所有商品单都没有评价，禁止这笔订单被选中
                disabled: !this.hasComment(record)
            })
        };

        const orderHear = (<Table pagination={false}
            rowSelection={rowSelection}
            columns={this.renderColumns()}
            dataSource={list.toJS()}
            onChange={(pagination, filters, sorter) => this.onChange(pagination, filters, sorter)} />);

        let self = this;
        // 以下三个字段均用来控制pages中的checkbox的状态
        // 全选按钮是否可用：至少存在一条有评价的订单
        let pageSelectDisabled = !list.some(order => self.hasComment(order))
        // 全选标识状态：当前页所有有评价的订单都已被选中。需要对selectedRowKeys.length做判断，否则如果当前页所有订单都没有评价时会返回true
        let selectAll = selectedRowKeys.length !== 0 && list.filterNot(order => !self.hasComment(order) || OrderedSet(selectedRowKeys).has(order.get('tid'))).isEmpty();
        // 是否处于中间状态：全选状态为false且已经有订单被选中
        let indeterminate = !selectAll && !list.filter(order => OrderedSet(selectedRowKeys).has(order.get('tid'))).isEmpty();

        return (
            <div>
                <Spin spinning={loading}>
                    {this.renderToolBar()}
                    <div className="order-list-table">
                        <div className="order-list-table-hd">{orderHear}</div>
                        <div className="order-list-table-bd">
                            {
                                list.isEmpty() ? <EmptyBody /> : list.map((order, index) => <OrderIterm key={index}
                                    order={order}
                                    deleteComment={this.handleDeleteComment}
                                    showCommentDialog={this.showCommentDialog}
                                    updateCommentShowState={this.updateCommentShowState}
                                    selectRow={(tid) => this.selectRow(tid)}
                                    selectedRowKeys={OrderedSet(selectedRowKeys)} />)
                            }
                        </div>
                    </div>
                    {
                        list.isEmpty() ? null : <Pages form={this.props.form}
                            pageSelectDisabled={pageSelectDisabled}
                            indeterminate={indeterminate}
                            selectAll={selectAll}
                            selectAll4Page={(selectAll) => this.selectAll4Page(selectAll)} />
                    }
                </Spin>
                <Modal title="评价详情" visible={this.state.commentVisible} footer={false}
                    onOk={this.handleOk} onCancel={this.handleCancel}
                    width="580px">
                    <CommentDetail form={this.props.form} />
                </Modal>
            </div>
        )
    }


    /**
     * 渲染toolBar
     * @returns {XML}
     */
    renderToolBar() {
        let disabled = this.props.list.filter(order => this.hasComment(order)).isEmpty();
        return (
            <Row className="table-toolbar">
                <Col span={12}>
                    <Button type="ghost" disabled={disabled} onClick={this.handleDeleteComments}>批量删除</Button>
                </Col>
            </Row>
        );
    }


    /**
     * 扩展最后一列
     * @returns {*|{options, browsertest, dist, rhino, rhinolessc}|Buffer|Array.<T>|string}
     */
    renderColumns() {
        // let { filterName, filters } = this.state; 
        // const _this = this;
        return orderColumns.concat([
            {
                title: '买家评价内容',
                width: 250,
                key: 'comment',
                className: "ant-table-th-right pr8 va-t"
            },
            {
                title: '',
                width: 385,
                key: '',
                className: "ant-table-th-right pr8 va-t"
            }
            // 一期场景化先不做评价状态过滤，等订单改造完成之后再做 OF1264
            // {
            //     title: filterName,
            //     width: 385,
            //     key: 'filter',
            //     className: "ant-table-th-right pr8 va-t",
            //     filters: [
            //         { text: '所有评价', value: 'ALL' },
            //         { text: '待评价', value: 'WAIT_COMMENT' },
            //         { text: '未回复', value: 'WAIT_REPLY' },
            //         { text: '已回复', value: 'REPLIED' },
            //         { text: '已删除', value: 'DELETE' }
            //     ],
            //     filterMultiple: false,
            //     filteredValue: filters
            // }
        ])
    }


    /**
     * 全选操作
     * @param selected
     * @param selectedRows
     * @param changeRows
     */
    selectAll(selected, selectedRows, changeRows) {
        let selectedRowKeys = [];
        let self = this;
        selected && selectedRows.forEach(row => {
            // 只有有评价的订单才能被选中
            if (self.hasComment(row) && selectedRowKeys.indexOf(row.tid) < 0) {
                selectedRowKeys.push(row.tid)
            }
        });
        this.setState({ selectedRowKeys });
    }


    /**
     *选择列操作
     * @param tid
     */
    selectRow(tid) {
        let selectedRowKeys = OrderedSet(this.state.selectedRowKeys);
        this.setState({
            selectedRowKeys: selectedRowKeys[selectedRowKeys.has(tid) ? 'delete' : 'add'](tid).toJS()
        })
    }


    /**
     * 给分页页面使用的全选操作
     * @param selectAll
     */
    selectAll4Page(selectAll) {
        let selectedRowKeys = [];
        let self = this;
        selectAll && this.props.list.forEach(order => {
            // 只有有评价的订单才能被选中
            if (self.hasComment(order)) {
                selectedRowKeys.push(order.get('tid'))
            }
        });
        this.setState({ selectedRowKeys });
    }

    /**
     * 判断这笔订单是否有评价
     * @param {*} order 
     */
    hasComment(order) {
        let simpleOrder = order;
        if (typeof order.toJS === 'function') {
            simpleOrder = order.toJS();
        }
        return simpleOrder.itemOrders.some(itemOrder => typeof itemOrder.comment !== 'undefined')
    }

    /**
     * 修改订单转测
     * @param pagination
     * @param filters
     * @param sorter
     */
    onChange(pagination, filters, sorter) {
        console.log(filters);
    }



    filter(value, record) {
        this.setState({
            filterName: value
        });
        return true;
    }

    showCommentDialog = (oid) => {
        this.props.setCommentDetail(oid);
        this.setState({
            commentVisible: true
        });
    }

    handleOk = (e) => {
        this.setState({
            commentVisible: false
        });
    }

    handleCancel = (e) => {
        this.setState({
            commentVisible: false
        });
    }

    /**
     * 删除评价
     * @param oid 商品单编号, 一条评价对应一个商品单编号
     */
    handleDeleteComment = (oid) => {
        Modal.confirm({
            content: '确定删除吗?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => this.deleteComments([oid]),
        });


    }

    /**
     * 批量删除评价
     */
    handleDeleteComments = (e) => {
        e.preventDefault();
        // 根据选中的订单编号列表tids获取对应的商品单编号列表oids
        let tids = this.state.selectedRowKeys;
        if (tids.length === 0) {
            message.warning('请先选择要删除的评价', 2);
            return;
        }
        let oids = [];
        this.props.list.forEach(order => {
            if (tids.indexOf(order.get('tid')) < 0) {
                return;
            }
            order.get('itemOrders').forEach(itemOrder => {
                // 某个商品单的评价可能被单独删掉了，需要过滤掉
                if (!!itemOrder.get('comment')) {
                    oids.push(itemOrder.get('oid'))
                }
            })
        })
        // 删除评价
        Modal.confirm({
            content: '确定删除吗?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                this.deleteComments(oids);
                // 批量删除时需要重置复选框选中状态
                this.setState({
                    selectedRowKeys: []
                });
            },
        });
    }

    deleteComments = (oids) => {
        this.props.deleteComments({ oids })
    }

    updateCommentShowState = (params) => {
        this.props.updateCommentShowState(params)
    }
}